__author__ = 'anorberg'

"""
A library of loosely-related utility methods to perform various operations on data tables.
"""

def cleave(table, columnId):
    """
    Split a TSV-like data table into an unordered collection of tables based on the value of a given column.
    
    Parameters:
      table -- a sequence of objects that support the index operator with the value columnId.
      columnId -- an object to use as an index into the objects contained in table.
    
    Returns:
      A dict mapping the possible values of columnId to lists of elements in table. The value of item[columnId] is
      guaranteed to have equalled the value in the key at the time the cleave was performed. The lists are
      guaranteed to be in the same order the elements were retrieved from table, simply collated out into
      different collections.
    
    Mutates:
      table will be iterated over, but not queried in any other way. Each element in table will be indexed
      exactly once, by column ID. Objects are not being copied in any way- the cleaved sublists are
      shallow copies, so changes to the elements in them will write through to the original table, although
      changes to the sublist structure will not.
    """
    ret = {}
    for record in table:
        item = record[columnId]
        if item not in ret:
            ret[item] = []
        ret[item].append(record)
    
    return ret